import 'dart:async';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_static/shelf_static.dart';
import 'package:wch/constant/config_constant.dart';
import 'package:wch/page/home.dart';
import 'package:wch/page/login.dart';
import 'package:wch/page/test2.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/package_info_utils.dart';

import 'constant/resource_constant.dart';
import 'helper/mqtt.dart';
import 'helper/preferences_helper.dart';
import 'networking/api.dart';

void main() async{
  // WidgetsFlutterBinding.ensureInitialized(); //不加这个强制横/竖屏会报错

  if (kReleaseMode){
    baseUrl = debugBaseUrl;
  }else {
    baseUrl = debugBaseUrl;
  }

  ///使用前需先加载 webview
  _initWebView();
  ///提前加载 preference，后面调用时可以直接同步操作
  if (Platform.isAndroid) {
    PreferencesHelper.getPreferences().then((value) {
      bool isAgree = PreferencesHelper.getIsAgreePrivacy() ?? false;
      if (isAgree) {
        PackageInfoHelper.getPackageInfo();
      }
    });
  } else {
    PreferencesHelper.getPreferences();
    PackageInfoHelper.getPackageInfo();
  }

  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
    [
      DeviceOrientation.portraitUp, // 竖屏 Portrait 模式
      // DeviceOrientation.portraitDown,
      // DeviceOrientation.landscapeLeft, // 横屏 Landscape 模式
      // DeviceOrientation.landscapeRight,
    ],
  );

  Directory? webServerDir;
  if (Platform.isIOS) {
    webServerDir = await getApplicationDocumentsDirectory();
  } else {
    webServerDir = await getDownloadsDirectory();
  }
  initWebServer(webServerDir!);

  StreamSubscription<List<ConnectivityResult>> subscription = Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> connectivityResult) {
    // Received changes in available connectivity types!
    // This condition is for demo purposes only to explain every connection type.
    // Use conditions which work for your requirements.
    if (connectivityResult.contains(ConnectivityResult.mobile)) {
      // Mobile network available.
      reConnectMqtt();
    } else if (connectivityResult.contains(ConnectivityResult.wifi)) {
      // Wi-fi is available.
      // Note for Android:
      // When both mobile and Wi-Fi are turned on system will return Wi-Fi only as active network type
      reConnectMqtt();
    } else if (connectivityResult.contains(ConnectivityResult.ethernet)) {
      // Ethernet connection available.
      reConnectMqtt();
    } else if (connectivityResult.contains(ConnectivityResult.vpn)) {
      // Vpn connection active.
      // Note for iOS and macOS:
      // There is no separate network interface type for [vpn].
      // It returns [other] on any device (also simulator)
      reConnectMqtt();
    } else if (connectivityResult.contains(ConnectivityResult.bluetooth)) {
      // Bluetooth connection available.
      reConnectMqtt();
    } else if (connectivityResult.contains(ConnectivityResult.other)) {
      // Connected to a network which is not in the above mentioned networks.
      reConnectMqtt();
    } else if (connectivityResult.contains(ConnectivityResult.none)) {
      // No available network types
      isNetworking = false;
      LogUtils.log('-网络不可用-');
    }
  });

  runApp(const WCHApp());
}

void reConnectMqtt() {
  if (!isNetworking) {
    LogUtils.log('-重新连接 mqtt-');
    reConnect();
  }
  isNetworking = true;
}


void initWebServer(Directory webServerDir) async{
  String path = webServerDir!.path;
  LogUtils.log('path=$path');
  final handler = Cascade()
      .add(createStaticHandler(p.join(path, '')))
      .handler;

  final server = await shelf_io.serve(handler, 'localhost', 8080);
  LogUtils.log('Serving at http://${server.address.host}:${server.port}');

  savedFile(webServerDir, 'images/index.html', 'index.html');
  savedFile(webServerDir, 'images/index-CZwJW8_v.js', 'index-CZwJW8_v.js');
  savedFile(webServerDir, 'images/OPPOSans-Regular-Dh2mlh0d.ttf', 'OPPOSans-Regular-Dh2mlh0d.ttf');

}

void readFile(Directory webServerDir) async {
  List<FileSystemEntity> list = webServerDir.listSync();
  for(int i = 0; i < list.length; i ++) {
    LogUtils.log('path=${list[i].path}');
  }
}

void savedFile(Directory webServerDir, String assetPath, savePath) async {
  ByteData bytes = await rootBundle.load(assetPath);
  final String path = '${webServerDir!.path}/$savePath';
  writeToFile(bytes, path);
}
Future<void> writeToFile(ByteData data, String path) {
  final buffer = data.buffer;
  return File(path).writeAsBytes(
      buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
}

Future<void> _initWebView() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (Platform.isAndroid) {
    await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);

    var swAvailable = await AndroidWebViewFeature.isFeatureSupported(
        AndroidWebViewFeature.SERVICE_WORKER_BASIC_USAGE);
    var swInterceptAvailable = await AndroidWebViewFeature.isFeatureSupported(
        AndroidWebViewFeature.SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST);

    if (swAvailable && swInterceptAvailable) {
      AndroidServiceWorkerController serviceWorkerController =
      AndroidServiceWorkerController.instance();

      serviceWorkerController.serviceWorkerClient = AndroidServiceWorkerClient(
        shouldInterceptRequest: (request) async {
          print(request);
          return null;
        },
      );
    }
  }
}
///全局 路由管理，页面内可 import 之后，使用页面出栈入栈等事件(生命周期)
final RouteObserver<Route<dynamic>> routeObserver = RouteObserver();

class WCHApp extends StatelessWidget {

  const WCHApp({super.key});
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 812),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context, child) {
        return MaterialApp(
          title: '脑电睡眠监测系统',
          navigatorKey: WCHApp.navigatorKey,
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            // This is the theme of your application.
            //
            // Try running your application with "flutter run". You'll see the
            // application has a blue toolbar. Then, without quitting the app, try
            // changing the primarySwatch below to Colors.green and then invoke
            // "hot reload" (press "r" in the console where you ran "flutter run",
            // or simply save your changes to "hot reload" in a Flutter IDE).
            // Notice that the counter didn't reset back to zero; the application
            // is not restarted.
              primaryColor: themeBGC,
              primarySwatch: Colors.lightBlue),
          home: Test2(data: 1, child: null,),
          navigatorObservers: [routeObserver],
          builder: (context, widget) {
            EasyLoading.init();

            return MediaQuery(
              ///设置文字大小不随系统设置改变
              data: MediaQuery.of(context).copyWith(textScaler: const TextScaler.linear(1.0)),
              child: FlutterEasyLoading(child:widget!),
            );
          },

          ///添加路由观察者
          ///优点，不需要上下文也能做跳转
          routes: {
            '/login': (BuildContext context) => const LoginPage(),
            // '/MeditationRecordList': (BuildContext context) => RecordPage(title: '冥想记录', type: 2, callback: (){}),
          },
        );
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Future<void> _initWebView() async {
    WidgetsFlutterBinding.ensureInitialized();
    if (Platform.isAndroid) {
      await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);

      var swAvailable = await AndroidWebViewFeature.isFeatureSupported(
          AndroidWebViewFeature.SERVICE_WORKER_BASIC_USAGE);
      var swInterceptAvailable = await AndroidWebViewFeature.isFeatureSupported(
          AndroidWebViewFeature.SERVICE_WORKER_SHOULD_INTERCEPT_REQUEST);

      if (swAvailable && swInterceptAvailable) {
        AndroidServiceWorkerController serviceWorkerController =
        AndroidServiceWorkerController.instance();

        serviceWorkerController.serviceWorkerClient = AndroidServiceWorkerClient(
          shouldInterceptRequest: (request) async {
            print(request);
            return null;
          },
        );
      }
    }
  }
}
